"""
This example demonstrates most basic operations with single model
"""
import asyncio

from tortoise import Tortoise, fields, run_async
from tortoise.models import Model


class Event(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
    datetime = fields.DatetimeField(null=True)

    class Meta:
        table = "event"

    def __str__(self):
        return self.name


import logging

fmt = logging.Formatter(
    fmt="%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
import sys
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.ERROR)
sh.setFormatter(fmt)

# will print debug sql
logger_db_client = logging.getLogger("db_client")
logger_db_client.setLevel(logging.DEBUG)
logger_db_client.addHandler(sh)

logger_tortoise = logging.getLogger("tortoise")
logger_tortoise.setLevel(logging.DEBUG)
logger_tortoise.addHandler(sh)

async def run():
    from urllib.parse import quote

    MYSQL_DB_URL = f'mysql://root:{quote("kexin@kexin2021")}@192.168.1.80/learn_db'
    await Tortoise.init(db_url=MYSQL_DB_URL, modules={"models": ["__main__"]})
    await Tortoise.generate_schemas()

    event = await Event.create(name="Test")

    await Event.filter(id=event.id).update(name="Updated name")

    print(await Event.filter(name="Updated name").first())
    # >>> Updated name

    await Event(name="Test 2").save()
    print(await Event.all().values_list("id", flat=True))
    # >>> [1, 2]
    print(await Event.all().values("id", "name"))
    # >>> [{'id': 1, 'name': 'Updated name'}, {'id': 2, 'name': 'Test 2'}]



async def run2():
    from urllib.parse import quote

    MYSQL_DB_URL = f'mysql://root:{quote("kexin@kexin2021")}@192.168.1.80/learn_db'
    await Tortoise.init(db_url=MYSQL_DB_URL, modules={"models": ["__main__"]})


    print(await Event.filter().first())
    # >>> Updated name


if __name__ == "__main__":
    run_async(run2())